package cn.hpclub.server.controller.admin;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import cn.hpclub.server.bean.OrgNode;
import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.model.SysUser;
import cn.hpclub.server.service.product.ProductService;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.JsonRender;

import cn.hpclub.server.model.KnowledgeBase;
import cn.hpclub.server.service.KnowledgeBaseService;
import cn.hpclub.server.util.InterfaceUtil;

public class KnowledgeBaseController extends BaseAdminController<KnowledgeBase>{
    static String               HTML_LIST             = "/admin/knowledge_base_list.tpl";                      // 机构管理页
    private static final String URL_TEMPLATE_PROVINCE = "/template/admin/file/知识库导入模板-省级.xls";
    private static final String URL_TEMPLATE_CITY     = "/template/admin/file/知识库导入模板-地市.xls";
    private static final Logger logger                = LoggerFactory.getLogger(KnowledgeBaseController.class);

    public void list(){
        initTypeList();
        initCityList();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        String sqlSelect = KnowledgeBase.dao.getSqlSelect();
        String sqlExceptSelect = KnowledgeBase.dao.getSqlExceptSelect(searchInfo);
        findByPageForSearch(sqlSelect, sqlExceptSelect);
        setAttrs(searchInfo);
        render(HTML_LIST);
    }

    public void export(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        String sqlSelect = KnowledgeBase.dao.getSqlSelect4Export();
        String sqlExceptSelect = KnowledgeBase.dao.getSqlExceptSelect(searchInfo);
        JSONObject result = KnowledgeBaseService.service.exportData(sqlSelect, sqlExceptSelect);
        renderJson(result.toJSONString());
    }

    public void template(){
        boolean isProvince = isProvinceAccount();
        if(isProvince){
            renderFile(URL_TEMPLATE_PROVINCE);
        } else{
            renderFile(URL_TEMPLATE_CITY);
        }
    }

    public void delete(){
        String ids = getDeleteIds();
        if(ids.length() == 0){
            ajaxJsonErrorMessage("未选中数据");
            return;
        }
        int count = Db.update("delete from knowledge_base where id in(" + ids + ")");
        Db.update("delete from knowledge_base_org where knowledge_id in(" + ids + ")");
        if(count > 0){
            ajaxJsonSuccessMessage("删除成功");
        } else{
            ajaxJsonErrorMessage("删除失败");
        }
    }

    private String getDeleteIds(){
        String[] ids = getParaValues("ids");
        StringBuffer sb = new StringBuffer();
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                sb.append(ids[i]);
                if(i < (ids.length - 1)){
                    sb.append(",");
                }
            }
        }
        return sb.toString();
    }

    private boolean isProvinceAccount(){
        int provinceId = InterfaceUtil.getIdTop();
        int userOrgId = InterfaceUtil.getOrgId();
        boolean isProvince = userOrgId == provinceId;
        return isProvince;
    }

    private void initTypeList(){
        List<Entry<String, String>> typeList = KnowledgeBaseService.service.getTypeList();
        setAttr("type_id", 0);
        setAttr("typeList", typeList);
    }

    private void initCityList(){
        List<Entry<String, String>> cityList = KnowledgeBaseService.service.getCityLevelOrgList();
        setAttr("city_id", cityList.isEmpty() ? 0 : cityList.get(0).getValue());
        setAttr("cityList", cityList);
    }

    @Before(Tx.class)
    public void upload(){
        Map<String, Object> result = KnowledgeBaseService.service.importData(this, getFile());
        render(new JsonRender(result).forIE());
    }


    private void initTypesNotWithAll(){
        List<Entry<String, Integer>> typeList = KnowledgeBaseService.service.getTypeListForDetail();
        //List<Entry<String, String>> typeList = KnowledgeBaseService.service.getTypeList();
        //typeList = typeList.stream().filter(entry -> !"0".equals(entry.getValue())).collect(Collectors.toList());
        setAttr("typeList", typeList);
    }

    public void add(){
        List<Entry<String, String>> cityList = KnowledgeBaseService.service.getCityLevelOrgList();
        setAttr("ortherCitys",cityList);
        setAttr("selectCitys",new ArrayList<Entry<String, String>>());
        initTypesNotWithAll();
        render("/admin/knowledge_input.tpl");
    }
    public  void edit(){
        int id = getParaToInt("id");
        if(id==0){
            add();
        }
        KnowledgeBase knowledgeBase = new KnowledgeBase().dao.findById(id);
        knowledgeBase.set("detail",knowledgeBase.get("detail"));
        setAttr("knowledgeBase",knowledgeBase);
        List<Record> list = KnowledgeBaseService.service.getkbOrgByKbId(id);
        List<Entry<String, String>> selectCityList = new ArrayList<>();
        List<Entry<String, String>> cityList = KnowledgeBaseService.service.getCityLevelOrgList();
        for (Entry<String, String> entry : cityList) {
            String value = entry.getValue();
            for (Record record : list) {
                if(value.equals(record.get("org_id").toString())){
                    selectCityList.add(entry);
                    break;
                }
            }
        }
        cityList.removeAll(selectCityList);
        setAttr("selectCitys",selectCityList);
        setAttr("ortherCitys",cityList);
        //initCityList();
        initTypesNotWithAll();
        render("/admin/knowledge_input.tpl");
    }
    public void save(){
        long id = getParaToInt("knowledgeBaseId",-1);
        String name = getPara("name");
        String type = getPara("type");
        String code = getPara("code");
        String detail = getPara("detail");

        try {
            detail = java.net.URLDecoder.decode(detail,   "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String enabled = getPara("enabled");

        int userId = InterfaceUtil.getAdminId();
        SysUser sysUser = SysUser.dao.findById(userId);
        KnowledgeBase knowledgeBase = new KnowledgeBase().dao.findById(id);
        int is_gov = InterfaceUtil.getGovEnterpriseFlag();
        int org_id = sysUser.getInt(SysUser.ORG_ID);
        String city_ids = getPara("city_ids");
        KnowledgeBase existsKnowledge = KnowledgeBase.dao.getModelByName(name,is_gov,org_id);
        if(existsKnowledge != null && existsKnowledge.getLong("id") > 0){
            existsKnowledge.set("name",name);
            existsKnowledge.set("type",type);
            existsKnowledge.set("code",code);
            existsKnowledge.set("detail",detail);
            existsKnowledge.set("enabled",enabled);
            existsKnowledge.set("modi_date",new Date());
            existsKnowledge.set("modi_by",userId);
            long id1 = existsKnowledge.getLong("id");
            long id2 = knowledgeBase!=null?knowledgeBase.getLong("id"):-1;
            boolean flag = id1 != id2 ? true : false;
            if(knowledgeBase!= null && flag){
                knowledgeBase.delete();
                deleteKnowledgeBaseOrg(id2);
            }
            existsKnowledge.update();
            id = existsKnowledge.getLong("id");
        }else{
            if(knowledgeBase== null){
                knowledgeBase = new KnowledgeBase();
                knowledgeBase.set("is_gov",is_gov);
                knowledgeBase.set("created_date",new Date());
                knowledgeBase.set("created_by",userId);
                knowledgeBase.set("created_org_id",org_id);
            }
            knowledgeBase.set("name",name);
            knowledgeBase.set("type",type);
            knowledgeBase.set("code",code);
            knowledgeBase.set("detail",detail);
            knowledgeBase.set("enabled",enabled);
            knowledgeBase.set("modi_date",new Date());
            knowledgeBase.set("modi_by",userId);
            if(id!=-1){
                knowledgeBase.update();
            }else{
                if(knowledgeBase.save()){
                    id = knowledgeBase.getLong("id");
                }
            }
        }
        updateKbOrg(id,city_ids);
        redirect("/knowledgeBase/list");
    }
    private int deleteKnowledgeBaseOrg(long kbId){
        return Db.update("delete from knowledge_base_org where knowledge_id=?",kbId);
    }
    private void updateKbOrg(long knowledge_id,String city_ids){
        String[] cityIdArr;
        if(city_ids.contains(",")){
            cityIdArr = city_ids.split(",");
        }else{
            cityIdArr = new String[]{city_ids};
        }
        StringBuffer sb = new StringBuffer("insert into knowledge_base_org (`knowledge_id`,`org_id`) values");
        StringBuffer values = new StringBuffer();

        OrgNode root = InterfaceUtil.getOrgTree(InterfaceUtil.getIdTop(), 1, false);
        String rootId = root.getId()+"";
        for (String org_id : cityIdArr) {
            if(rootId.equals(org_id)){
                values = new StringBuffer();
                List<OrgNode> orgNodes = root.getSubNode();
                for (OrgNode orgNode : orgNodes) {
                    org_id = orgNode.getId()+"";
                    values.append("("+knowledge_id+","+org_id+")").append(",");
                }
                break;
            }
            values.append("("+knowledge_id+","+org_id+")").append(",");
        }
        sb.append(values);
        String insertSql = sb.toString();
        insertSql = insertSql.substring(0,insertSql.length()-1);
        String sql  ="delete from knowledge_base_org where knowledge_id = ?";
        Db.update(sql,knowledge_id);
        Db.update(insertSql);
    }

}
